<template>
  <el-breadcrumb :separator-icon="ArrowRight">
    <el-breadcrumb-item :to="{ path: '/' }">首页(登录)</el-breadcrumb-item>
    <el-breadcrumb-item>RBAC管理</el-breadcrumb-item>
    <el-breadcrumb-item>用户管理-配置菜单</el-breadcrumb-item>
  </el-breadcrumb>
  
  <div>
    <!-- 搜索区域 -->
    <el-card style="margin-top: 10px;">
      <el-form :inline="true" :model="searchData" class="demo-form-inline">
        <el-form-item label="用户名">
          <el-input v-model="searchData.userNickname" placeholder="请输入用户名" clearable />
        </el-form-item>
        <!-- <el-form-item label="角色">
          <el-select v-model="searchData.roleName" placeholder="请选择角色" style="width: 120px;" clearable>
            <el-option
              v-for="item in roleOptions"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
              
            />
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="getUsers">查询</el-button>
          <el-button type="success" @click="addUser">添加用户</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card style="margin-top: 10px;">
      <el-table :data="userData" border style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="序号" width="75" align="center" />
        <el-table-column prop="userName" label="用户名" align="center" />
        <el-table-column prop="userNickname" label="昵称" align="center" />
        <el-table-column prop="roleName" label="角色" align="center" />
        <el-table-column prop="menuName" label="功能" align="center" />
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scoped">
            <el-tag v-if="scoped.row.status == '0'" type="success">启用</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center" >
          <template v-slot="scoped">
          {{ moment(scoped.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}
        </template>
    </el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template #default="scoped">
            <el-button type="warning" size="small" @click="editUser(scoped.row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div style="margin-top: 20px; text-align: center;">
        <el-pagination
          v-model:current-page="page.PageIndex"
          v-model:page-size="page.PageSize"
          :page-sizes="[5, 10, 20, 50]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.totalCount"
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户弹窗 -->
    <el-dialog v-model="userDialogVisible" :title="userDialogTitle" width="600px" draggable>
      <el-form ref="userFormRef" :model="userForm" :rules="userRules" label-width="100px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userForm.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="userPass">
          <el-input v-model="userForm.userPass" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="昵称" prop="userNickname">
          <el-input v-model="userForm.userNickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-checkbox-group v-model="userForm.roleIds">
            <el-checkbox 
              v-for="item in roleOptions" 
              :key="item.roleId"
              :value="item.roleId" 
              :label="item.roleName"
            />
          </el-checkbox-group>
        </el-form-item>
        
        <!-- 权限配置区域 -->
        <el-divider content-position="left">权限配置</el-divider>
        <div>
          
          <el-form-item label="溯源管理:">
            <el-checkbox v-model="model.showcheck" />
           <el-form-item label="菜单权限:">
          <el-checkbox-group v-model="userForm.menuIds" :disabled="model.showcheck!=true">
            <el-checkbox 
              v-for="item in menuPermissionData" 
              :key="item.menuId"
              :value="item.menuId" 
              :label="item.menuName"
            />
          </el-checkbox-group>
        </el-form-item>
        </el-form-item>
        </div>
        <!-- <el-form-item label="功能权限">
          <el-checkbox-group v-model="userForm.functionPermissions">
            <el-checkbox 
              v-for="item in functionPermissionData" 
              :key="item.permissionId"
              :value="item.permissionId" 
              :label="item.permissionName"
            />
          </el-checkbox-group>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUserForm(userFormRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'
import { ArrowRight } from '@element-plus/icons-vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { useCounterStore } from "@/stores/counter"
import { dataRead, dataWrite } from '@/Utils/Http'
import moment from 'moment'

const model = reactive({
  showcheck: false,
})

// 类型定义
interface UserForm {
  userId: number
  userName: string
  userPass: string
  userNickname: string
  roleIds: number[]
  menuIds: number[]
  // functionPermissions: number[]
}

interface SearchData {
  userNickname: string
  roleName: string
}

interface Page {
  PageIndex: 1
  PageSize: 5
  totalCount: 0
  pageCount: 0
}

interface Role {
  roleId: number
  roleName: string
}

interface Permission {
  menuId: number
  menuName: string
}

// 变量初始化
const counter = useCounterStore()
const router = useRouter()
const loading = ref(false)

// 用户相关
const userData = ref<any>([])
const userFormRef = ref<FormInstance>()
const userForm = reactive<UserForm>({
  userId: 0,
  userName: '',
  userPass: '',
  userNickname: '',
  roleIds: [],
  menuIds: [],
  // functionPermissions: []
})

// 搜索和分页
const searchData = reactive<SearchData>({
  userNickname: '',
  roleName: ''
})

const page = reactive<Page>({
  PageIndex: 1,
  PageSize: 5,
  totalCount: 0,
  pageCount: 0
})

// 弹窗相关
const userDialogVisible = ref(false)
const userDialogTitle = ref('添加用户')

// 角色和权限数据
const roleOptions = ref<Role[]>([])
const menuPermissionData = ref<Permission[]>([])
// const functionPermissionData = ref<Permission[]>([])

// 表单验证规则
const userRules = reactive<FormRules<UserForm>>({
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  userPass: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  userNickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ]
})

// 生命周期钩子
onMounted(() => {
  getUsers()
  getRoleOptions()
  getMenuPermissions()
  // getFunctionPermissions()
})

// 监听分页变化
watch(page, () => {
  getUsers()
})

// 获取用户列表
const getUsers = () => {
  loading.value = true
  dataRead.get('/BaseData/UserByMenu', {
    params: {
      userNickname: searchData.userNickname,
      roleName: searchData.roleName,
      PageIndex: page.PageIndex,
      PageSize: page.PageSize
    }
  }).then(res => {
    userData.value = res.data.data.data
    page.totalCount = res.data.data.totalCount
    page.pageCount = res.data.data.pageCount
  }).catch(err => {
    ElMessage.error('获取用户列表失败')
    console.error(err)
  }).finally(() => {
    loading.value = false
  })
}

// 获取角色选项
const getRoleOptions = () => {
  dataRead.get('/BaseData/BindRole').then(res => {
    roleOptions.value = res.data.data
  }).catch(err => {
    ElMessage.error('获取角色列表失败')
    console.error(err)
  })
}

// 获取菜单权限
const getMenuPermissions = () => {
  // 使用死值数据
  // menuPermissionData.value = [
  //   { permissionId: 1, permissionName: '添加', permissionUrl: '/add' },
  //   { permissionId: 2, permissionName: '修改', permissionUrl: '/upd' },
  //   { permissionId: 3, permissionName: '删除', permissionUrl: '/del' },
  //   { permissionId: 4, permissionName: '查询', permissionUrl: '/query' }
  // ]
  
  // 如果需要从API获取，可以取消注释以下代码
  dataRead.get('/BaseData/BindMenuPer').then(res => {
    menuPermissionData.value = res.data.data
  }).catch(err => {
    ElMessage.error('获取菜单权限失败')
    console.error(err)
  })
}

// 获取功能权限
// const getFunctionPermissions = () => {
//   // 使用死值数据
//   functionPermissionData.value = [
//     { permissionId: 101, permissionName: '浏览', permissionUrl: '/browse' },
//     { permissionId: 102, permissionName: '新增', permissionUrl: '/add' },
//     { permissionId: 103, permissionName: '修改', permissionUrl: '/edit' },
//     { permissionId: 104, permissionName: '删除', permissionUrl: '/delete' },
//     { permissionId: 105, permissionName: '导出', permissionUrl: '/export' },
//     { permissionId: 106, permissionName: '导入', permissionUrl: '/import' }
//   ]
  
  // 如果需要从API获取，可以取消注释以下代码
  // dataRead.get('/BaseData/FunctionPermissions').then(res => {
  //   functionPermissionData.value = res.data.data
  // }).catch(err => {
  //   ElMessage.error('获取功能权限失败')
  //   console.error(err)
  // })
//}

// 添加用户
const addUser = () => {
  userDialogTitle.value = '添加用户'
  userForm.userId = 0
  userForm.userName = ''
  userForm.userPass = ''
  userForm.userNickname = ''
  userForm.roleIds = []
  userForm.menuIds = []
  // userForm.functionPermissions = []
  
  userDialogVisible.value = true
}

// 编辑用户
const editUser = (row: any) => {
  userDialogTitle.value = '编辑用户'
  userForm.roleIds = row.roleId || []
  userForm.menuIds = row.menuId || []
  // userForm.functionPermissions = row.functionPermissions || []
  
  Object.assign(userForm, row)
  userDialogVisible.value = true
}


// 提交用户表单
const submitUserForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  
  await formEl.validate((valid) => {
    if (valid) {
      if (userForm.userId == 0) {
        // 添加用户
        if (userForm.roleIds.length == 0) {
          ElMessage.error('请选择角色')
          return
        }
        if (userForm.menuIds.length == 0) {
          ElMessage.error('请选择功能')
          return
        }
        
        dataWrite.post('/BaseData/AddUserByEnum', userForm).then(res => {
          if (res.data.code == 300) {
            ElMessage.success('添加成功')
            userDialogVisible.value = false
            getUsers()
          } else if (res.data.data == -1) {
            ElMessage.error(res.data.message)
          } else {
            ElMessage.error('添加失败')
          }
        })
      } else {
        // 修改用户
        dataWrite.post('/BaseData/UpdUserByEnum', userForm).then(res => {
          if (res.data.code == 400) {
            ElMessage.success('修改成功')
            userDialogVisible.value = false
            getUsers()
          } else {
            ElMessage.error('修改失败')
          }
        })
      }
    }
  })
}

</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-tag {
  margin-right: 8px;
}

.el-checkbox {
  margin-right: 15px;
}
</style>
